-module(stomptest).
-compile(export_all).

%% TODO:
%% 1. Basic send/receive (done)
%% 2. Parse the message data into a message record
%% 3. Implemenent acknowledgement by client
%% 4. Replay subscriptions
%% 5. Implement transactions
%% 6. Unsubscribe
%% 7. Clean-up code

-record(state, {client_socket, is_connected=false}).
%% A client which periodically sends a message into MQ and reads teh message from the queue in
%% a separate thread

start() ->
    spawn(?MODULE, sender, [0]),
    spawn(?MODULE, receiver, []),

    io:get_line('Enter any key to exit>'),
    halt().

sender(T) ->
    State = erlst:connect("localhost", 61613),
    CSocket = State#state.client_socket,    
    erlst:message(CSocket, "/queue/FOO.BAR", io_lib:fwrite("Hello World @ ~p:~p from ~p", [date(), time(), T])),
    sleep(infinity),
    ok.

receiver() ->
    State = erlst:connect("localhost", 61613),
    CSocket = State#state.client_socket,
    erlst:subscribe(CSocket, "/queue/FOO.BAR", [{ack, auto}]),
    erlst:start_message_receiver(CSocket),
    print_incoming_messages(),
    ok.
    
print_incoming_messages() ->
    receive
        {message, Data} ->
            io:fwrite("..... Message:~p~n", [Data]);
        Any ->
            io:fwrite(">>>>> Any:~p~n", [Any])         
    end,
    sleep(100),
    print_incoming_messages().

sleep(T) ->
    receive
    after T ->
            true
    end.
        

